<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *地址表
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('addresses')) {
            Schema::create('addresses', function (Blueprint $table) {
                $table->id();
                $table->string('name')->comment('地区名称');
                $table->string('ad_code')->comment('地区编号');
                $table->unsignedInteger('parent_id')->comment('上级id')->index();
                $table->unsignedInteger('level')->comment('所属级别');
                $table->timestamps();
            });
        }

        //插入数据
        $this->addAddress();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addresses');
    }

    /**
     * 将数据插入到表格中
     */
    public function addAddress()
    {
        $filePath = base_path() . '/database/data-with-code.json';
        $file = fread(fopen($filePath, 'r'), filesize($filePath));
        $addArray = json_decode($file, true);
        //将数组写入数据库
        $this->sequence($addArray);
    }


    /**
     * @param $addresses 地址数组
     * @param $parent_id 父级id
     * @param $level 级别
     */
    public function sequence($addresses, $parent_id = 0, $level = 1)
    {
        foreach ($addresses as $address) {
            $addModel=\App\Models\Address::create([
                'name' => $address['title'],
                'ad_code' => $address['ad_code'],
                'parent_id' => $parent_id,
                'level' => $level
            ]);
            //判断不为空
            if (!empty($address['child'])) {
                $this->sequence($address['child'],$addModel->id,$level+1);
            }else {
                return ;
            }
        }
    }
}
